///@Description(描述)     xxxx
///@author(作者)          zhangyinhong
///@create(时间)          2025-08-28 08:59

/// 应用信息工具类
import 'package:package_info_plus/package_info_plus.dart';
import 'package:flutter/foundation.dart';

/// 应用信息工具类
class AppPackageInfo {
  static PackageInfo? _info;

  static Future<PackageInfo> get _packageInfo async {
    return _info ??= await PackageInfo.fromPlatform();
  }

  static Future<String> get appName async => (await _packageInfo).appName;
  static Future<String> get version async => (await _packageInfo).version;
  static Future<String> get packageName async => (await _packageInfo).packageName;
  static Future<String> get buildNumber async => (await _packageInfo).buildNumber;

  /// 获取应用信息摘要
  static Future<Map<String, String>> get summary async {
    final info = await _packageInfo;
    return {'应用名称': info.appName, '包名': info.packageName, '版本号': info.version, '构建号': info.buildNumber, '完整版本': 'v${info.version}+${info.buildNumber}'};
  }

  /// 检查版本是否需要更新
  static Future<bool> needsUpdate(String newVersion) async {
    try {
      final currentVersion = await version;
      return _compareVersions(currentVersion, newVersion) < 0;
    } catch (e) {
      debugPrint('版本比较失败: $e');
      return false;
    }
  }

  /// 获取版本比较结果 (-1: 当前版本低, 0: 相同, 1: 当前版本高)
  static Future<int> compareVersion(String otherVersion) async {
    try {
      final currentVersion = await version;
      return _compareVersions(currentVersion, otherVersion);
    } catch (e) {
      debugPrint('版本比较失败: $e');
      return 0;
    }
  }

  /// - 返回 -1：version1 < version2（第一个版本号较低）
  /// - 返回  0：version1 = version2（两个版本号相同）
  /// - 返回  1：version1 > version2（第一个版本号较高）
  ///
  static int _compareVersions(String version1, String version2) {
    List<int> v1 = version1.split('.').map((e) => int.tryParse(e) ?? 0).toList();
    List<int> v2 = version2.split('.').map((e) => int.tryParse(e) ?? 0).toList();

    int maxLength = v1.length > v2.length ? v1.length : v2.length;

    for (int i = 0; i < maxLength; i++) {
      int num1 = i < v1.length ? v1[i] : 0;
      int num2 = i < v2.length ? v2[i] : 0;

      if (num1 < num2) return -1;
      if (num1 > num2) return 1;
    }

    return 0;
  }
}
